package hgx.spring.cloud.lession.productrepertory.hystrix.batch;/**
 * Created by liujun on 2018/4/21.
 */

import com.netflix.hystrix.HystrixCollapser;
import com.netflix.hystrix.HystrixCollapserKey;
import com.netflix.hystrix.HystrixCollapserProperties;
import com.netflix.hystrix.HystrixCommand;
import com.netflix.hystrix.HystrixCommandKey;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;

import hgx.spring.cloud.lession.productrepertory.api.ProductRepository;
import hgx.spring.cloud.lession.productrepertory.vo.ReponseProductVo;

/**
 * 请求合并处理
 *
 * @author hugx
 * @create 2018-04-21 10:31
 */
public class ProductGetByIdCollapseHystrixCommand extends HystrixCollapser<List<ReponseProductVo>, ReponseProductVo, Long> {
    private ProductRepository productRepository;
    private Long id;
    private static final HystrixCommandKey GetById_Key = HystrixCommandKey.Factory.asKey("product_getByIdCollapse");

    public ProductGetByIdCollapseHystrixCommand(ProductRepository productRepository, Long id) {
        super(Setter.withCollapserKey(HystrixCollapserKey.Factory.asKey("product_getByIdCollapse")).andCollapserPropertiesDefaults(HystrixCollapserProperties.defaultSetter().withTimerDelayInMilliseconds(100)));
        this.productRepository = productRepository;
        this.id = id;
    }

    @Override
    public Long getRequestArgument() {
        return id;
    }

    @Override
    protected HystrixCommand<List<ReponseProductVo>> createCommand(Collection<CollapsedRequest<ReponseProductVo, Long>> collapsedRequests) {
        List<Long> ids = new ArrayList<>(collapsedRequests.size());
        ids.addAll(collapsedRequests.stream().map(CollapsedRequest::getArgument).collect(Collectors.toList()));


        return new ProductGetByIdBatchHystrixCommand(productRepository, ids);
    }

    @Override
    protected void mapResponseToRequests(List<ReponseProductVo> batchResponse, Collection<CollapsedRequest<ReponseProductVo, Long>> collapsedRequests) {
        int count = 0;
        for (CollapsedRequest<ReponseProductVo, Long> collapsedRequest : collapsedRequests) {
            ReponseProductVo reponseProductVo = batchResponse.get(count++);

            collapsedRequest.setResponse(reponseProductVo);
        }
    }


}
